package com.fileupload.fileupload.listener;

import com.alibaba.excel.EasyExcel;
import com.fileupload.fileupload.domain.entity.UploadExcelEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.io.File;
import java.util.concurrent.Executor;
import java.util.concurrent.Semaphore;

@Slf4j
@Component
public class FileUploadConsumer {
    @Resource(name = "readExcelSemaphore")
    private Semaphore semaphore;
    @Resource(name = "readExcelTaskExecutor")
    private Executor executor;
    @Resource(name = "redisTemplate")
    private RedisTemplate redisTemplate;
    @Autowired
    private ExcelDataListener dataListener;
    /**
     * 接收消息,接收excel文件上传完毕后向mq发送到文件地址消息
     * @param filePath
     */
    @RabbitListener(queues = "file-upload-queue")
    public void excelUploadMessage(String filePath) {
        log.info("文件上传消息：{}", filePath);
        // 尝试获取信号量
        if (semaphore.tryAcquire()) {
            // 创建文件读取任务
            executor.execute(() -> {
                // 执行文件读取任务
                log.info("开始读取文件：{}", filePath);
                EasyExcel.read(filePath, UploadExcelEntity.class, dataListener).sheet().doRead();
                // 释放信号量
                semaphore.release();
                // 删除本地的临时文件和redis上面的key
                String[] split = filePath.split("\\\\");
                String fileName = split[split.length - 1];
                String fileId = fileName.split("\\.")[0];
                // 判断redis中是否存在key
                if (redisTemplate.hasKey(fileId + "_chunks")) {
                    // 清空redis中list根据对应的key
                    redisTemplate.opsForList().trim(fileId + "_chunks", 1, 0);
                    log.info("清空redis中key为：{}的list列表",fileId + "_chunks");
                }
                // 删除本地的临时文件
                File file = new File(filePath);
                if (file.exists()){
                    file.delete();
                    log.info("删除本地临时文件成功");
                }
            });
        } else {
            log.info("文件读取任务正在执行中，无法再次执行");
            // todo 没有拿到信号量创建重试任务
        }
    }

}
